package com.mobile.check.activitys;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import cn.droidlover.xdroidmvp.base.BaseListActivity;
import cn.droidlover.xdroidmvp.base.BaseRecyclerAdapter;
import cn.droidlover.xdroidmvp.base.RecyclerViewHolder;
import cn.droidlover.xdroidmvp.kit.NLog;
import cn.droidlover.xdroidmvp.kit.NToast;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import com.mobile.check.beans.BluetoothInfo;
import com.mobile.check.app.R;

import com.mobile.check.present.BluetoothPresent;

/**
 * 类名: BluetoothListActivity
 * 作者: 李学伟
 * 日期: 2020年10月14日 10:06
 * 描述:
 */
public class BluetoothListActivity extends BaseListActivity<BluetoothInfo, BluetoothPresent> {

    private BluetoothManager bluetoothmanger;
    BluetoothAdapter bluetoothAdapter;
    List<String> mackList = new ArrayList<>();

    BluetoothInfo targetInfo;

    @Override
    public void initView() {
        super.initView();
        titleTv.setText("蓝牙");
        rightTv.setText("扫描");
        rightTv.setVisibility(View.VISIBLE);
        mRefreshLayout.setEnableLoadmore(false);
        mRefreshLayout.setEnableRefresh(false);
    }

    @Override
    public void onRightClick(View view) {
        super.onRightClick(view);
        startScan();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        //立即启动扫描线程
        bluetoothmanger = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothmanger.getAdapter();
        registBlueBooth();
        startScan();
    }

    @Override
    public BaseRecyclerAdapter<BluetoothInfo> getAdapter() {
        return new BaseRecyclerAdapter<BluetoothInfo>(this) {
            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.item_bluetooth;
            }

            @Override
            public void bindData(RecyclerViewHolder holder, int position) {
                BluetoothInfo info = mBaseAdapter.getItemByPosition(position);
                holder.setText(R.id.titleTv, info.getName());
                holder.setText(R.id.macTv, "MAC：" + info.getMac());
                holder.setText(R.id.rssiTv, "RSSI：" + info.getRssi());
                holder.setText(R.id.codTv, "COD：" + info.getCod());
                holder.setText(R.id.bondTv, info.getBond());
                holder.setText(R.id.typeTv, "DeviceType：" + getP().toDeviceTypeString(info.getDeviceType()));

            }
        };
    }

    @Override
    public void itemClick(int position) {
        targetInfo = mBaseAdapter.getItemByPosition(position);
        Intent dataIntent = new Intent();
        dataIntent.putExtra("BluetoothInfo", targetInfo);
        setResult(Activity.RESULT_OK, dataIntent);
        finish();
//        showConnectDialog(targetInfo);
    }

    @Override
    public void getDataFromServer() {

    }

    @Override
    public void getIntentData() {

    }

    private void registBlueBooth() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.EXTRA_CONNECTION_STATE);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(mReceiver, filter);
    }

    @Override
    public BluetoothPresent newP() {
        return new BluetoothPresent();
    }


    private void startScan() {
        mBaseAdapter.removeAll();
        mackList.clear();
        if (!bluetoothAdapter.isEnabled()) {
            Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enabler, 1);
            return;
        }
        if (!bluetoothAdapter.isDiscovering()) {
            showLoadDialog("正在扫描蓝牙设备");
            Observable.create(new ObservableOnSubscribe<Object>() {
                @Override
                public void subscribe(ObservableEmitter<Object> e) throws Exception {
                    startDiscovery();
                    e.onNext(1);
                }
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Object>() {
                @Override
                public void accept(Object o) throws Exception {

                }
            });
        }
    }


    private void cancelScan() {
        disLoadDialog();
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        if (mBaseAdapter.getItemCount() == 0) {    //找到蓝牙设备
            NToast.shortToast(BluetoothListActivity.this, getString(R.string.actDiscovery_msg_not_find_device));
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

//    private void createBond(final BluetoothDevice bluetoothDevice) {
//        showLoadDialog("正在进行蓝牙配对");
//        Observable.create(new ObservableOnSubscribe<Boolean>() {
//            @Override
//            public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
//                boolean result = BluetoothCtrl.createBond(bluetoothDevice);
//                e.onNext(result);
//            }
//        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
//            @Override
//            public void accept(Boolean aBoolean) throws Exception {
//                NLog.d(TAG, "aBoolean=" + aBoolean);
//            }
//        }, new Consumer<Throwable>() {
//            @Override
//            public void accept(Throwable throwable) throws Exception {
//                throwable.printStackTrace();
//            }
//        });
//    }

//    private void connect(final String mac) {
//        showLoadDialog("正在进行蓝牙连接");
//        Observable.just(mac).map(new Function<String, Boolean>() {
//            @Override
//            public Boolean apply(String mac) {
//                boolean connected = GlobalPoolApplication.instance.createConn(mac);
//                return connected;
//            }
//        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
//            @Override
//            public void accept(Boolean result) throws Exception {
//                if (!result) {
//                    showToast("蓝牙连接失败");
//                } else {
//                    SharedPref.getInstance(BluetoothListActivity.this).putString("blueboothMac", mac);
//                    showToast("蓝牙连接成功");
//                    Intent data = new Intent();
//                    if (!TextUtils.isEmpty(targetInfo.getName())) {
//                        data.putExtra("bleName", targetInfo.getName());
//                    } else {
//                        data.putExtra("bleName", targetInfo.getMac());
//                    }
//                    setResult(Activity.RESULT_OK, data);
//                    finish();
//                }
//                disLoadDialog();
//            }
//        }, new Consumer<Throwable>() {
//            @Override
//            public void accept(Throwable throwable) throws Exception {
//                throwable.printStackTrace();
//                showToast("蓝牙连接失败!");
//                disLoadDialog();
//            }
//        });
//
//    }


    /**
     * 注册搜索蓝牙设备的广播
     */
    private void startDiscovery() {
        startScanBluetooth();
    }

    private void startScanBluetooth() {
        // 判断是否在搜索,如果在搜索，就取消搜索
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        // 开始搜索
        bluetoothAdapter.startDiscovery();
    }

    /**
     * 蓝牙广播接收
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent dataIntent) {
            String action = dataIntent.getAction();
            BluetoothDevice device = dataIntent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            NLog.d("BroadcastReceiver", "action=" + action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                delaFound(dataIntent);
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                cancelScan();
            }
        }
    };

    private void delaFound(Intent data) {
        BluetoothDevice device = data.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        BluetoothInfo info = new BluetoothInfo(device.getName(), device.getAddress());
        Bundle b = data.getExtras();
        info.setRssi(String.valueOf(b.get(BluetoothDevice.EXTRA_RSSI)));
        info.setCod(String.valueOf(b.get(BluetoothDevice.EXTRA_CLASS)));

        if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
            info.setBond(getString(R.string.actDiscovery_bond_bonded));
        } else {
            info.setBond(getString(R.string.actDiscovery_bond_nothing));
        }

        String EXTRA_DEVICE_TYPE = "android.bluetooth.device.extra.DEVICE_TYPE";
        String sDeviceType = String.valueOf(b.get(EXTRA_DEVICE_TYPE));
        if (!sDeviceType.equals("null")) {
            info.setDeviceType(sDeviceType);
        } else {
            info.setDeviceType("-1");
        }
        Log.d("BluetoothListActivity", "info=" + info);
        if (!mackList.contains(device.getAddress())) {
            mackList.add(device.getAddress());
            mBaseAdapter.add(info);
        }
    }

    @Override
    public boolean isNotWorkConnect() {
        return false;
    }


//    private void showConnectDialog(BluetoothInfo info) {
//        SubmitTipDialog tipDialog = new SubmitTipDialog(this, new SubmitTipDialog.SlectClickListener() {
//            @Override
//            public void submitClick() {
//                BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(targetInfo.getMac());
//                if (bluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
//                    createBond(bluetoothDevice);
//                } else {
//                    connect(targetInfo.getMac());
//                }
//            }
//
//            @Override
//            public void cancelClick() {
//
//            }
//        });
//        BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(targetInfo.getMac());
//        String rightTxt = "连接";
//        if (bluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
//            rightTxt = "配对";
//        }
//        tipDialog.display("提示", "您将连接 " + info.getName() + " 检测设备，是否继续连接？", "取消", rightTxt);
//    }


}
